const https = require('https');
const axios = require("axios").default;
const router = require('koa-router')();

const scripts = require('./scripts/capitaland');

const statusOptions = {
  method: 'GET',
  url: 'http://www.mercury2.cn/nginx/status',
  headers: { 'user-agent': 'vscode-restclient', 'content-type': 'text/plain' }
};

router.prefix('/api/monitor');

router.get('/status/:aggregate/:interval', async (ctx, next) => {
  let interval = ctx.params.interval;

  let rs = await ctx.getDbHelper('我的MySQL').queryForList(scripts.GetMonitorDatas, {
    dbName: 'monitor',
    tableName: 'capitaland_prod_status',
    interval: interval,
    aggregate: ctx.params.aggregate,
    currentDate: ctx.request.query.current
  });

  if (rs.datas) {
    rs.datas = rs.datas.sort((a, b) => {
      return new Date(a.RecordDateTime).getTime() - new Date(b.RecordDateTime).getTime();
    });

    if (rs.datas && rs.datas.length > 0) {
      let prev = rs.datas[0];

      rs.datas.forEach(d => {
        if (d != prev) {
          d.RequestInteval = (d.Requests - prev.Requests).toFixed(2);
        }

        prev = d;
      });

      rs.datas[0].RequestInteval = 0;
    }
  }

  ctx.body = rs;
});

router.get('/clearDatas', async (ctx, next) => {
  let rs = await ctx.getDbHelper('我的MySQL').execute(scripts.ClearStatusDatas, {
    dbName: 'monitor',
    tableName: 'capitaland_prod_status'
  });

  ctx.body = rs;
});

router.post('/pullDatas', async (ctx, next) => {
  let rs = await pullDatas();

  ctx.body = rs;
});

let pullDatas = async function () {
  let response = await axios.request(statusOptions);

  let status = {
    dbName: 'monitor',
    tableName: 'capitaland_prod_status',
    connections: 0,
    server: 0,
    accepts: 0,
    requests: 0,
    reading: 0,
    writing: 0,
    waiting: 0
  };
  let datas = response.data.split('\n');

  if (datas.length > 4) {
    let con = datas[0].split(':')[1].trim();
    let requests = datas[2].trim().split(' ');

    status.connections = parseInt(con);
    status.server = parseInt(requests[0].trim());
    status.accepts = parseInt(requests[1].trim());
    status.requests = parseInt(requests[2].trim());

    let reds = datas[3].trim().split(' ');

    status.reading = parseInt(reds[1].trim());
    status.writing = parseInt(reds[3].trim());
    status.waiting = parseInt(reds[5].trim());
  }

  console.log(status);

  return await router.context.getDbHelper().execute(scripts.AddMonitor, status);
};

// let failCounts = 0;
// let handler = setInterval(function () {
//   pullDatas().then(res => { }, reason => {
//     failCounts++;

//     if (failCounts > 30) {
//       clearInterval(handler);
//     }
//   });
// }, 10000);

module.exports = router;